<head>
  <style> body { margin: 0; } </style>

  <script type="importmap">{ "imports": {
    "react": "https://esm.sh/react",
    "react-dom": "https://esm.sh/react-dom/client"
  }}</script>

<!--  <script type="module">import * as React from 'react'; window.React = React;</script>-->
<!--  <script src="../../src/packages/react-force-graph-2d/dist/react-force-graph-2d.js" defer></script>-->
</head>

<body>
  <div id="graph"></div>

  <script src="//unpkg.com/@babel/standalone"></script>
  <script type="text/jsx" data-type="module">
    import ForceGraph2D from 'https://esm.sh/react-force-graph-2d?external=react';
    import React, { useState, useEffect, useRef } from 'react';
    import { createRoot } from 'react-dom';
    import { forceCollide }  from 'https://esm.sh/d3-force-3d';

    const CollisionDetectionFG = () => {
      const fgRef = useRef();

      const [graphData, setGraphData] = useState({ nodes: [], links: [] });

      useEffect(() => {
        const fg = fgRef.current;

        // Deactivate existing forces
        fg.d3Force('center', null);
        fg.d3Force('charge', null);

        // Add collision and bounding box forces
        fg.d3Force('collide', forceCollide(4));
        fg.d3Force('box', () => {
          const SQUARE_HALF_SIDE = N * 2;

          nodes.forEach(node => {
            const x = node.x || 0, y = node.y || 0;

            // bounce on box walls
            if (Math.abs(x) > SQUARE_HALF_SIDE) { node.vx *= -1; }
            if (Math.abs(y) > SQUARE_HALF_SIDE) { node.vy *= -1; }
          });
        });

        // Generate nodes
        const N = 80;
        const nodes = [...Array(N).keys()].map(() => ({
          // Initial velocity in random direction
          vx: (Math.random() * 2) - 1,
          vy: (Math.random() * 2) - 1
        }));

        setGraphData({ nodes, links: [] });
      }, []);

      return <ForceGraph2D
        ref={fgRef}
        graphData={graphData}
        cooldownTime={Infinity}
        d3AlphaDecay={0}
        d3VelocityDecay={0}
      />;
    };

    createRoot(document.getElementById('graph'))
      .render(<CollisionDetectionFG />);
  </script>
</body>